# 读取数据
data_cluster <- read.csv("seurat_clusters.csv")

# 计算每个ID中subtype的个数
subtype_counts <- table(data_cluster$ID, data_cluster$subtype)

# 计算每个ID中subtype的百分比
subtype_percentages <- prop.table(subtype_counts, margin = 1)

# 输出结果
print(subtype_percentages)

cibersort_barplot<-as.data.frame(subtype_percentages)


#柱状图可视化细胞占比预测
library(RColorBrewer)
library(ggplot2)

mypalette <- colorRampPalette(brewer.pal(8,"Set1"))


ggplot(cibersort_barplot,aes(Var1,Freq,fill = Var2)) + 
  geom_bar(position = "stack",stat = "identity") +
  coord_polar()+
  labs(fill = "Cluster",x = "",y = "Estiamted Proportion") + theme_bw() +
  theme(axis.text.x = element_blank()) + theme(axis.ticks.x = element_blank()) +
  scale_y_continuous(expand = c(0.01,0)) +
  scale_fill_manual(values = mypalette(25))

# 载入reshape2包
library(reshape2)


# 转换为短数据框
subtype_percentages_df <- dcast(cibersort_barplot, Var1 ~ Var2, value.var = "Freq")

# 将ID设置为rowname
colnames(subtype_percentages_df)<-c("ID","Cluster0","Cluster1","Cluster2","Cluster3","Cluster4","Cluster5","Cluster6","Cluster7")


# 输出结果
write.csv(subtype_percentages_df,"Proportion_TCGA.csv")





